import { setToken, getToken } from '@/utils/auth'
import { loginAPI } from '@/apis/user'

export default {
  namespaced: true, // 补充命名空间
  state: () => {
    return {
      token: getToken() || "",
    }
  },
  mutations: {
    clearUserInfo(state) {
      state.token = ""
      // 清除token
      setToken("")
    },
    setToken(state, newToken) {
      state.token = newToken
      // 设置token到cookie中
      setToken(newToken)
    }
  },
  actions: {
    async toLogin(ctx, { username, password }) {
      // 1. 调用接口
      const res = await loginAPI({ username, password })
      console.log(res)
      // 2. 提交mutation
      ctx.commit('setToken', res.data.token)
    },
  }
}
